/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;
	@Autowired
	private TbShopService tbShopService;
	@Autowired
	private WithDrawApplyService withDrawApplyService;
	@Autowired
	private UserTenementInfoService userTenementInfoService;
	@Autowired
	PC service;// 调用业务层方法
	@Autowired
	private CommunityService communityService;
	@Autowired
	private ShopAddService shopAddService;
	@Autowired
	private TbCommunityService tbCommunityService;
	@Autowired
	private TbMpWalletService tbMpWalletService;
	@Autowired
	private TbMsgNotifyService tbMsgNotifyService;
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}

	@RequestMapping(value = {"index"})
	public String index(User user, Model model) {
		return "modules/sys/userIndex";
	}

	@RequestMapping(value = {"list", ""})
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		List<Role> roleList = systemService.findAllRole();
		model.addAttribute("role",roleList);
        model.addAttribute("page", page);
		return "modules/sys/userList";
	}
	//系统消息通知
	@RequestMapping(value ="tbMsgNotityList")
	public String tbMsgNotityList(TbMsgNotify tbMsgNotify, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TbMsgNotify> page = tbMsgNotifyService.findMsgList(new Page<TbMsgNotify>(request, response), tbMsgNotify);
		model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/tbMsgNotifyList";
	}
	//将一系统消息改为已读getMsg
	@RequestMapping(value ="getMsg")
	public String getMsg(TbMsgNotify tbMsgNotify, HttpServletRequest request, HttpServletResponse response, Model model) {
		 tbMsgNotifyService.updateStatus(tbMsgNotify);
		 return "redirect:" + adminPath + "/sys/user/tbMsgNotityList?repage&status=0";
	}

	/**
	 * 物业费
	 * @param tbUserTenementInfo
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"listTenement", ""})
	public String listTenement(TbUserTenementInfo tbUserTenementInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		tbUserTenementInfo.setUid(UserUtils.getUser().getId());
		Page<TbUserTenementInfo> page = userTenementInfoService.findUserTenementInfoPage(new Page<TbUserTenementInfo>(request, response), tbUserTenementInfo);
        model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/userTenementList";
	}

	
	@ResponseBody
	@RequestMapping(value = {"listData"})
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		return page;
	}

	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		if(user.getId()!=null){
			UserArea us=new UserArea();
			us.setId(user.getId());
			UserArea userArea=communityService.getAreaByUserId(us);
			model.addAttribute("area",userArea);
		}
		List proviceList=service.showProvinceList();
		//在用户添加中，将商户和代理商从角色列表中移除
		List<Role> rlist=systemService.userAddRoleList();
		//如果是超级管理员可以添加系统管理员，海外店铺管理员，
		if(UserUtils.getUser().getId().equals("1")){
			for(int i=0;i<rlist.size();i++){
				Role role=(Role)rlist.get(i);
				String roid=role.getId();
				if(role.getId().equals("8")||role.getId().equals("2")||role.getId().equals("10")){
					rlist.remove(i);
					i--;
				}
			}
		}else{//系统管理员只能添加系统管理员
			for(int i=0;i<rlist.size();i++){
				Role role=(Role)rlist.get(i);
				String roid=role.getId();
				if(!role.getId().equals("1")){
					rlist.remove(i);
					i--;
				}
			}

		}
		model.addAttribute("proList",proviceList);// 存入作用域中
		model.addAttribute("user", user);
		model.addAttribute("allRoles",rlist);
		return "modules/sys/userForm";
	}
	//修改用户信息显示界面
	@RequestMapping(value = "formUser")
	public String formUser(User user, Model model) {
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		if(user.getId()!=null){
			UserArea us=new UserArea();
			us.setId(user.getId());
			UserArea userArea=communityService.getAreaByUserId(us);
			model.addAttribute("area",userArea);
		}
		model.addAttribute("proList", service.showProvinceList());// 存入作用域中
		model.addAttribute("user", user);
		//在用户添加中，将商户和代理商从角色列表中移除
		Role role=systemService.getRoleByUid(user.getId());
		model.addAttribute("role",role);
		return "modules/sys/userEdit";
	}
	//查看用户详情
	@RequestMapping(value = "view")
	public String view(User user, Model model) {
		User use=systemService.getUser(user.getId());
		//根据得到的用户id查询到他所在的省市区id
		UserArea us=new UserArea();
		us.setId(user.getId());
		UserArea userArea=communityService.getAreaByUserId(us);
		//根据用户id得到角色信息
		Role role=systemService.getRoleByUid(user.getId());
		model.addAttribute("role",role);
		model.addAttribute("area",userArea);
		model.addAttribute("user", user);
		return "modules/sys/userView";
	}

	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		user.setCompany(new Office(user.getProvinces()));
		user.setOffice(new Office(user.getProvinces()));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if (!beanValidator(model, user)){
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()){
			if (roleIdList.contains(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		List photo=user.getUploadUrl();
		if(photo!=null&&photo.size()>0){
			user.setPhoto((String)photo.get(0));
		}
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 删除用户物业信息
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "deleteUserTenementInfo")
	public String deleteUserTenementInfo(HttpServletRequest request,RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}try {
			TbUserTenementInfo tbUserTenementInfo = new TbUserTenementInfo();
			tbUserTenementInfo.setId(Integer.valueOf(request.getParameter("id")));
			userTenementInfoService.deleteUserTenementInfo(tbUserTenementInfo);
			addMessage(redirectAttributes, "删除用户成功");
		}catch(Exception e){
			addMessage(redirectAttributes, "删除用户失败");
	}
		return "redirect:" + adminPath + "/sys/user/listTenement?repage";
	}

	/**
	 * 删除用户
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		if (UserUtils.getUser().getId().equals(user.getId())){
			addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
		}else if (User.isAdmin(user.getId())){
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		}else{
			systemService.deleteUser(user);
			addMessage(redirectAttributes, "删除用户成功");
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}
	/**
	 * 启用或禁用用户
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "updateLoginFlag")
	public String updateLoginFlag(User user, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		if (UserUtils.getUser().getId().equals(user.getId())){
			addMessage(redirectAttributes, "禁用用户失败, 不允许禁用当前用户");
		}else if (User.isAdmin(user.getId())){
			addMessage(redirectAttributes, "禁用用户失败, 不允许禁用超级管理员用户");
		}else{
			if(user.getLoginFlag().equals("0")){
				user.setLoginFlag("1");
			}else{
				user.setLoginFlag("0");
			}
			systemService.updateLoginFlag(user);
			if(user.getLoginFlag().equals("0")){
				addMessage(redirectAttributes, "禁用用户成功");
			}else{
				addMessage(redirectAttributes, "启用用户成功");
			}

		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}
	/**
	 * 导出用户数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "用户数据"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
    		new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/listTenement?repage";
    }
	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list){
				try{
					if ("true".equals(checkLoginName("", user.getLoginName()))){
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					}else{
						failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser());
			new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 导出物业费用数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "exportTenement", method=RequestMethod.POST)
	public String exportTenementFile(TbUserTenementInfo tbUserTenementInfo,User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "物业费数据"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			tbUserTenementInfo.setUid(UserUtils.getUser().getId());
			Page<TbUserTenementInfo> page = userTenementInfoService.findUserTenementInfoPage(
					new Page<TbUserTenementInfo>(request, response,-1), tbUserTenementInfo);
			new ExportExcel("物业费数据", TbUserTenementInfo.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/listTenement?repage";
	}
	/**
	 * 导入物业费数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
    @RequestMapping(value = "importTenement", method=RequestMethod.POST)
    public String importTenementFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response,  RedirectAttributes redirectAttributes) {

		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/listTenement?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TbUserTenementInfo> list = ei.getDataList(TbUserTenementInfo.class);
			//小区插入
			TbCommunity tbCommunity = new TbCommunity();
			tbCommunity = communityService.insertCommunity(tbCommunity,list) ;

			for (TbUserTenementInfo tbUserTenementInfo : list){
				try{
					tbUserTenementInfo.setCommunityId(tbCommunity.getId());
					tbUserTenementInfo.setUid(UserUtils.getUser().getId());
					tbUserTenementInfo.setName(tbUserTenementInfo.getName());
					userTenementInfoService.insert(tbUserTenementInfo);
						successNum++;
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+tbUserTenementInfo.getName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+tbUserTenementInfo.getName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/listTenement?repage";
    }
	
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
    @RequestMapping(value = "import/templateTenement")
    public String importFileTemplateTenement(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物业表数据导入模板.xlsx";
    		List<TbUserTenementInfo> list = Lists.newArrayList(); /*list.add(UserUtils.getUser());*/
    		new ExportExcel("物业表数据", TbUserTenementInfo.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/listTenement?repage";
    }

	/**
	 * 验证登录名是否有效
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 用户信息显示及保存
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "info")
	public String info(User user, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		//根据uid查询得到role_id

		if (StringUtils.isNotBlank(user.getName())){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userInfo";
			}
			currentUser.setName(user.getName());
			currentUser.setPhoto(user.getPhoto());
			currentUser.setEmail(user.getEmail());
			currentUser.setPhone(user.getPhone());
			currentUser.setMobile(user.getMobile());
			currentUser.setRemarks(user.getRemarks());
			systemService.updateUserInfo(currentUser);
			model.addAttribute("message", "保存用户信息成功");
		}
		//根据id的到角色，如果角色中有代理商，则找到代理商的区域
		List<Role> rlist=systemService.seleceRoleIdByUid(currentUser.getId());
		for(Role role:rlist){
			if("2".equals(role.getId())||"8".equals(role.getId())||"f196ad2e6f3346868588bbb8ec9ace59".equals(role.getId())){
				//将代理商的区域放到所在的用户中，个人信息中显示
				User ares=systemService.selectAreas(currentUser.getId());
				currentUser.setProvinces(ares.getProvinces());
				currentUser.setCitys(ares.getCitys());
				currentUser.setRole(role);
				//如果是代理商显示余额，根据uid查询麻雀钱包得到金额
				TbMpWallet tbMpWallet=systemService.selectMoneyByUid(currentUser.getId());
				if(role.getId().equals("8")){
					//根据ui得到店铺id
					TbShop tbShop=systemService.selectShopByUid(currentUser.getId());
					model.addAttribute("shop",tbShop);

				}
				if(role.getId().equals("f196ad2e6f3346868588bbb8ec9ace59")){
					//根据ui得到店铺id
					TbShop tbShop=systemService.selectShopByUid(currentUser.getId());
					model.addAttribute("shop",tbShop);
				}
				model.addAttribute("tbMpWallet",tbMpWallet);
				model.addAttribute("role",role);
			}

		}
		model.addAttribute("user", currentUser);
		model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
	}
	/**
	 * 提现信息查看
	 * @param tbWithdrawApply
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "withDrawals")
	public String withDrawals(TbWithdrawApply tbWithdrawApply,  HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
//		tbWithdrawApply.setUid(Integer.valueOf(currentUser.getId()));  // 冲突报错、 Jyy
		tbWithdrawApply.setUid(currentUser.getId());
		if(Global.isDemoMode()){
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/withDrawApply";
		}
		Page<TbWithdrawApply> page = withDrawApplyService.findDrawApplyPage(new Page<TbWithdrawApply>(request, response), tbWithdrawApply);
		model.addAttribute("page", page);
		model.addAttribute("tbWithdrawApply", tbWithdrawApply);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/withDrawApply";
	}
	/**
	 * 平台提现信息查看
	 * @param tbWithdrawApply
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "withDrawalsAll")
	public String withDrawalsAll(TbWithdrawApply tbWithdrawApply,  HttpServletRequest request, HttpServletResponse response, Model model) {
		if(Global.isDemoMode()){
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/withDrawalsAll";
		}
		Page<TbWithdrawApply> page = withDrawApplyService.findDrawApplyPage(new Page<TbWithdrawApply>(request, response), tbWithdrawApply);
		model.addAttribute("page", page);
		model.addAttribute("tbWithdrawApply", tbWithdrawApply);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/withDrawalsAll";
	}
	/**
	 * 平台提现更改审核状态
	 * @param tbWithdrawApply
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updateWithDrawalStatus")
	public String updateWithDrawalStatus(TbWithdrawApply tbWithdrawApply,  HttpServletRequest request, HttpServletResponse response, Model model) {
		if(Global.isDemoMode()){
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/withDrawalsAll";
		}
		tbWithdrawApply.setAuditorStatus(request.getParameter("status"));
		withDrawApplyService.updateWithDrawalStatus(tbWithdrawApply);
		return "redirect:" + adminPath + "/sys/user/withDrawalsAll";
	}
	/**
	 * 钱包提现
	 * @param tbWithdrawApply
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "acceptWithDrawApply")
	public String acceptWithDrawApply(TbWithdrawApply tbWithdrawApply, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if(Global.isDemoMode()){
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/acceptWithDrawApply";
		}
		////todo: 11/26/2016 获取麻雀钱包余额 比对提现金额
		TbMpWallet mqTbMpWallet = tbMpWalletService.getByUID(currentUser.getId());
		int r = mqTbMpWallet.getTotalMoney().compareTo(tbWithdrawApply.getMoney());
		if(r < 0){
			model.addAttribute("message", "钱包余额不足");
		}else{
			tbWithdrawApply.setUid(currentUser.getId());
			withDrawApplyService.insert(tbWithdrawApply);
			model.addAttribute("message", "提现信息提交成功");
		}
		model.addAttribute("tbWithdrawApply", tbWithdrawApply);
		return "forward:" + adminPath + "/sys/user/toWithDrawApply";
	}
	@RequestMapping(value = "toWithDrawApply")
	public String toWithDrawApply(TbWithdrawApply tbWithdrawApply,TbMpWallet tbMpWallet, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if(Global.isDemoMode()){
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/acceptWithDrawApply";
		}
		tbMpWallet  = tbMpWalletService.getByUID(currentUser.getId());
		model.addAttribute("tbMpWallet", tbMpWallet);
		model.addAttribute("tbWithdrawApply", tbWithdrawApply);
		model.addAttribute("Global", new Global());
		return "modules/sys/acceptWithDrawApply";
	}
    /**
     * 账户中心
     * @param response
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "accountInfo")
    public String accountInfo(TbMpWalletStream tbMpWalletStream, HttpServletRequest request, HttpServletResponse response, Model model) {
        User currentUser = UserUtils.getUser();
		tbMpWalletStream.setUid(currentUser.getId());
            if(Global.isDemoMode()){
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/accountStream";
            }
        Page<TbMpWalletStream> page = tbShopService.findWalletStreamPage(new Page<TbMpWalletStream>(request, response), tbMpWalletStream);
        model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
        return "modules/sys/accountStream";
    }

	/**
	 * 店铺信息显示
	 * @param shop
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "storeInfo")
	public String storeInfo(TbShop shop, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		shop.setUid(currentUser.getId());
		shop = tbShopService.selectShop(shop);
		if (StringUtils.isNotBlank(shop.getName())){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/storeInfo";
			}
			model.addAttribute("message", "店铺信息成功");
		}
		//得到代理商所在的城市id
		User ares=shopAddService.userAreas(currentUser.getId());
		//根据城市得到区域集合
		int cid=Integer.parseInt(ares.getCitys());
		List<Areas> area1 = service.showAreaListBycid(cid);
		//小区,根据小区id得到小区名称
		if(shop.getId()!=null){
			TbCommunity tbCommunity=tbCommunityService.get(shop.getCommunityId());
			model.addAttribute("community",tbCommunity);
		}

		model.addAttribute("areasList",area1);
		model.addAttribute("shop", shop);
		model.addAttribute("Global", new Global());
		return "modules/sys/storeInfo";
	}
	/**
	 * 店铺信息保存以及更改
	 * @param shop
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveStoreInfo")
	public String saveStoreInfo(TbShop shop, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		shop.setUid(currentUser.getId());
		if (StringUtils.isNotBlank(shop.getName())){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/storeInfo";
			}
			tbShopService.saveStoreInfo(shop);
			model.addAttribute("message", "店铺信息成功");
		}
		model.addAttribute("shop", shop);
		model.addAttribute("Global", new Global());

		return storeInfo(shop,response,model);
	}


	/**
	 * 返回用户信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}
	
	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userModifyPwd";
			}
			if (SystemService.validatePassword(oldPassword, user.getPassword())){
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}
/**
	 * 修改店铺配送费
	 * @param packingFee
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "modifyPackingFee")
	public String modifyPackingFee(BigDecimal packingFee, Model model) {
		User user = UserUtils.getUser();
        TbShop shop = new TbShop();
        shop.setPackingFee(packingFee);
		shop.setUid(user.getId());
		TbShop isPacking=tbShopService.selectShop(shop);
		if(isPacking!=null){
			if (StringUtils.isNotBlank(packingFee+"")&&packingFee!=null){
				if(Global.isDemoMode()){
					model.addAttribute("message", "演示模式，不允许操作！");
					return "modules/sys/userModifyPackingFee";
				}
				try {
					tbShopService.updatePackingFee(shop);
					model.addAttribute("message", "修改配送费成功");
				}catch (Exception e){
					model.addAttribute("message", "修改配送费失败");
				}
			}
		}
		TbShop es=tbShopService.selectShop(shop);
		//user = systemService.getUser(user.getId());
		model.addAttribute("user", user);
		model.addAttribute("shop",es);
		return "modules/sys/userModifyPackingFee";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String officeId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i=0; i<list.size(); i++){
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_"+e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}

//	 查询所有省位
//	@RequestMapping("/modifyPwd")
//	public String showProvinceList(HttpServletRequest request, HttpServletResponse response) {
//
//		response.setContentType("text/html;charset=UTF-8");
//		HttpSession session = request.getSession();
//		session.setAttribute("proList", service.showProvinceList());// 存入作用域中
//		return "modules/sys/userModifyPwd";
//		//return "/index.jsp";
//
//	}
//
//	// 根据ajax返回到控制器的省id来查询相对应的城市名
//	@RequestMapping("/showCityListByPid")
//	public void showCityListByPid(HttpServletRequest request, HttpServletResponse response, int pid) throws IOException {
//
//		response.setContentType("text/html;charset=UTF-8");
//		System.out.println(pid);// 打印前台ajax传来的省id
//		List<Citys> city1 = service.showCityListByPid(pid);
//		JSONArray json = JSONArray.fromObject(city1);// 将集合转化为json格式
//		response.getWriter().print(json.toString());
//		response.getWriter().flush();
//		response.getWriter().close();
//
//	}
//
//	// 根基ajax返回到控制器的城市id来查询相对应的区、县
//	@RequestMapping("/showTownListByCid")
//	public void showTownListByCid(HttpServletRequest request, HttpServletResponse response, int cid) throws IOException {
//		response.setContentType("text/html;charset=UTF-8");
//		System.out.println(cid);// 打印前台ajax传来的城市id
//		List<Areas> area1 = service.showAreaListBycid(cid);
//		JSONArray json = JSONArray.fromObject(area1);// 将集合转化为json格式
//		response.getWriter().print(json.toString());
//		response.getWriter().flush();
//		response.getWriter().close();
//
//	}
//	@InitBinder
//	public void initBinder(WebDataBinder b) {
//		b.registerCustomEditor(List.class, "roleList", new PropertyEditorSupport(){
//			@Autowired
//			private SystemService systemService;
//			@Override
//			public void setAsText(String text) throws IllegalArgumentException {
//				String[] ids = StringUtils.split(text, ",");
//				List<Role> roles = new ArrayList<Role>();
//				for (String id : ids) {
//					Role role = systemService.getRole(Long.valueOf(id));
//					roles.add(role);
//				}
//				setValue(roles);
//			}
//			@Override
//			public String getAsText() {
//				return Collections3.extractToString((List) getValue(), "id", ",");
//			}
//		});
//	}
	@RequestMapping("/checkAgentAreas")
	public void checkAgentAreas(HttpServletRequest request, HttpServletResponse response,String pid,String cityid){
		response.setContentType("text/html;charset=UTF-8");
		User user=new User();
		user.setProvinces(pid);
		user.setCitys(cityid);
		int rows=systemService.checkAgentAreas(user);
		try{
			if(rows>0){
				response.getWriter().print("1");
			}else{
				response.getWriter().print("0");
			}
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e){
			e.printStackTrace();
		}

		}
	@RequestMapping("/checkShopByCommunit")
	public void checkShopByCommunit(HttpServletRequest request, HttpServletResponse response,Integer communityId) {
		response.setContentType("text/html;charset=UTF-8");
		User user = new User();
		TbShop tbShop=tbShopService.checkShopByCommunity(communityId);
		try {
			if (tbShop!=null) {
				response.getWriter().print("1");
			} else {
				response.getWriter().print("0");
			}
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
